package cn.yuanqiao.web.controller.archive.qzj.controller;

import cn.yuanqiao.archive.qzj.domain.YqdaQzjFile;
import cn.yuanqiao.archive.qzj.service.YqdaQzjFileService;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.core.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.enums.BusinessType;
import cn.yuanqiao.common.exception.ServiceException;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/archive/qzjfile")
public class YqdaQzjFileController extends BaseController {
    @Autowired
    private YqdaQzjFileService qzjFileService;

    @Log(title = "获取全宗卷电子文件列表", businessType = BusinessType.SELECT)
    @GetMapping(value = "/{ID}")
    public AjaxResult getInfo(@PathVariable("ID") Long qzjId)
    {
        return AjaxResult.success(qzjFileService.selectList(qzjId));
    }

    @Log(title = "电子文件上传", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("qzjId")Long qzjId, @RequestParam("file") MultipartFile file)
    {
        return AjaxResult.success(qzjFileService.insertYqdaQzjFile(file,qzjId));
    }

    @Log(title = "文件预览", businessType = BusinessType.BROWSE)
    @PostMapping("/view/{id}")
    public ResponseEntity<Resource> view(@PathVariable("id") Long id){
        YqdaQzjFile qzjFile = qzjFileService.getById(id);

        // 加载文件作为资源
        File file = new File(qzjFile.getFilePath());
        /// 设置文件路径
        //String filePath = "C:\\Users\\Lenovo\\Desktop\\" + fileName;
        //File file = new File(filePath);

        // 确保文件存在
        if (!file.exists() || !file.canRead()) {
            throw new ServiceException("文件不存在或不可读!");
        }

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamResource resource = new InputStreamResource(fileInputStream);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .contentLength(file.length())
                    .body(resource);
        } catch (IOException e) {
            // 记录异常信息
            logger.error(e.getMessage(),e);
            throw new ServiceException("读取文件时发生错误"+e.getMessage());
        }
    }

    @Log(title = "删除全宗文件", businessType = BusinessType.DELETE)
    @DeleteMapping("/del")
    public AjaxResult remove(@RequestBody JSONObject ID) {
        String[] idsStr = ID.getString("ids").split(",");
        Long[] ids = new Long[idsStr.length];
        for (int i = 0; i < idsStr.length; i++) {
            ids[i] = Long.valueOf(idsStr[i]);
        }
        return AjaxResult.success(qzjFileService.delYqdaQzjFile(ids));
    }

}
